package middleware

import (
	"github.com/gin-gonic/gin"
)

func GlobalExceptionHandle(c *gin.Context) {
	defer func() {
		if r := recover(); r != nil {
			c.JSON(200, gin.H{
				"code": "500",
				"msg":  errorToString(r),
			})
			c.Abort()
		}
	}()
	c.Next()
}

// recover错误，转string
func errorToString(r interface{}) string {
	switch v := r.(type) {
	case error:
		return v.Error()
	default:
		return r.(string)
	}
}
